# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import  json,os,sys,commands,paramiko,datetime,random,uuid

from django.http import HttpResponse,Http404,FileResponse,StreamingHttpResponse
from django.shortcuts import render_to_response,render,redirect
from django.http import  HttpRequest
from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth.decorators import login_required
from django.utils.safestring import mark_safe
from models import  UserGroup,UserInfo,HostInfo,Product,UserLog,Host
#
import  saltapi
from  vpn import  MysqlApi
import  tasks
salt = saltapi.SaltApi()
vpn_mysql = MysqlApi()


import  logging,shutil,time

# from operation import  models
#group by分组用

from django.db.models import Count, Min, Max, Sum
# from utils import pagination

#视图装饰器,@require_http_methods(["GET", "POST"])
# from django.views.decorators.http import require_http_methods
# @require_http_methods('POST')
#@require_POST()



#定义语言环境
if sys.getdefaultencoding() != 'utf-8':
    reload(sys)
    sys.setdefaultencoding('utf-8')



def log_in(func):
    '''身份认证装饰器，
    '''
    def wrapper(request,*args,**kwargs):
        if not request.session.get("userid"):
            return redirect("/op/login")
        return  func(request,*args, **kwargs)
    return wrapper









logger = logging.getLogger(__name__)



# Create your views here.

#定义首页面展示

def index(request):

	u = request.session.get('userid')
	if request.session.get('is_login', None):
		return render(request, 'ftp_upload.html')
	else:
		return render(request, 'opertion/login.html')




#用户、组查询

def user_list(request):
	user_list = UserInfo.objects.all().order_by('id')
	usergroup_list = UserGroup.objects.all()
	for u in user_list:
		print  u.username
		print u.user_group.group_name
		print u.user_type_id

	return  render(request,'user_list.html',{"user_list":user_list,"usergroup_list":usergroup_list})
#用户添加
def user_add(request):
	if request.method == 'POST':
		u = request.POST.get('user')
		p = request.POST.get('pwd')
		g = request.POST.get('gid')
		print u,p,g
		UserInfo.objects.create(username=u,password=p,user_group_id=g)
	return  redirect('/op/user_list')





#用户删除
def user_del(request,gid):
	UserInfo.objects.filter(id=gid).delete()

	return  HttpResponse('删除ok')

#编辑用户
def user_edit(request,eid):
	if request.method == "GET":
		obj = UserInfo.objects.filter(id=eid).first()
		return render(request, 'op/user_edit.html', {'obj': obj})
	elif request.method == 'POST':
		uid = request.POST.get('id')
		u = request.POST.get('username')
		p = request.POST.get('password')
		UserInfo.objects.filter(id=uid).update(username=u, password=p)
		print  uid,u,p
		return  redirect('/op/user_list')

def detail(request,question_id):
	try:
		# return HttpResponse("You're looking at question %s." % question_id )
		question = Question.objects.get(pk=question_id)
	except Question.DoesNotExist:
		raise Http404("Question does not exist")
	# question = get_object_or_404(Question, pk=question_id)
	return render(request, 'op/detail.html', {'question': question})


# http://127.0.0.1:8000/op/add?a=3&b=2
# class MyView(View):
#     def get(self, request, *args, **kwargs):
#         return HttpResponse('Hello, World!')
# from myapp.views import MyView
#
# urlpatterns = [
#     path('mine/', MyView.as_view(), name='my-view'),
# ]

def add(View):
	def get(self, request, *args, **kwargs):
		return HttpResponse('Hello, World!')
	# a = request.GET['a']
	# b = request.GET['b']
	# c = int(a) + int(b)
	# return HttpResponse(c)
# http://127.0.0.1:8000/op/add2/888892/7161617
# def add2(request,a,b):
#
# 	c = int(a) + int(b)
# 	return HttpResponse(int(c))

from .forms import FilesForm

def add2(request):
	pass





def logout(request):
	try:
		request.session.clear()
		return redirect('/op/login/')
	except KeyError:
		pass
	return HttpResponse("You're logged out.")



def login(request):
	if request.method == 'GET':
		return render(request,'opertion/login.html')
	elif request.method == 'POST':
		#从数据中获取用户信息
		u = request.POST.get('user')
		p = request.POST.get('pwd')
		request.session['userid'] = u
		request.session['is_login'] = True
		request.session.set_expiry(7200)
		login_ip = request.META['REMOTE_ADDR']
		# print  request.user.is_authenticated
		obj = UserInfo.objects.filter(username=u,password=p,).first()
		#如果查不到就是none
		if obj:
			return redirect('/op/index')
		else:
			return  redirect('/op/login')


from django.views.decorators.cache import cache_page

def orm(request):
	f = request.FILES['image']
	print  '上传的文件名=========>>>>',f.name

	path = request.POST.get('remotePath')
	print path
	with open('./media/uploads/'+f.name, 'wb+') as destination:
		for chunk in f.chunks():
			destination.write(chunk)
	return HttpResponse('ok')

	#判断host主机up状态
	# host_list = salt.runner_status('status')['up']
	# print  host_list
	# for host in host_list:
	# 	result = salt.get_minions_grains(host)
	# 	kernel = result['kernel']
	# 	kernel_v = result['kernelrelease']
	# 	kernel = kernel + kernel_v
	# 	num_cpus = result['num_cpus']
	# 	list = result['fqdn_ip4']
	# 	print  list
	# 	if list :
	# 		ip = result['fqdn_ip4'][0]
	# 	else:
	# 		ip = host
	# 	mem_total = result['mem_total']
	# 	hostname = result['host']
	# 	sn = uuid.uuid1()
	#
	# 	#内存格式化入库
	# 	if mem_total <= 4000:
	# 		mem_total = '4G'
	# 	elif mem_total > 4000 and mem_total <= 8000:
	# 		mem_total = '8G'
	# 	elif mem_total > 8000 and mem_total <= 16000:
	# 		mem_total = '16G'
	# 	info = {
	# 		"ip":ip,
	# 		"kernel":kernel,
	# 		"num_cpus":num_cpus,
	# 		"mem_total":mem_total,
	# 		"hostname":hostname,
	# 		"sn":sn
	# 	}
	# 	print  info
	# 	#判断库中是否有这个ip
	# 	ku_ip = HostInfo.objects.filter(ip=ip)
	# 	if ku_ip:
	# 		print '数据库中已经存在%s的配置信息' % ip
	# 	else:
	# 		HostInfo.objects.create(**info)

	# user = models.UserInfo.objects.all()
		# print  i['username']
	# group_dict = {}
	# group_dict = {i['username']: i['password'] for i in models.UserInfo.objects.values('username', 'password')}
	# user = models.UserInfo.objects.values('username', 'password')
	# print user
	# for i in user:
	# 	group_dict = {i['username']:i['password']}
	# 	print  set(group_dict.items())
		# print  sorted(list(set(group_dict.items())))
	# g_name = UserGroup02.objects.all()
	# print g_name
	# return  HttpResponse('orm')
	# data_test = {"departmentname":'1111'}
	# data_test = json.dumps(data_test)
	# print  data_test
	# if request.method == 'POST':
	# 	return HttpResponse(data_test,content_type='application/json')
	# list = []
	# if request.method == 'POST':
	# 	for i in range(50):
	# 		u = '0000' + str(i)
	# 		list.append(u)
	# 	print  list
	# 	return  HttpResponse(json.dumps(data_test))
	# return  render(request,'opertion/page2.html')
	# from django.contrib.auth.hashers import make_password
	# user.password = make_password(password)  # 明文密码经过加密处理
	# user.save()
#pdf文件
	# from reportlab.pdfgen import canvas
	# from  io import BytesIO
	#
	# response = HttpResponse(content_type='application/pdf')
	# response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'
	# buffer = BytesIO()
	# p = canvas.Canvas(buffer)
	# p.drawString(100, 100, "Hello world3333333333333.")
	# p.showPage()
	# p.save()
	#
	# pdf = buffer.getvalue()
	# buffer.close()
	# response.write(pdf)
#csv文件
	# import csv,codecs
	# response = HttpResponse(content_type='text/csv')
	# response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
	#
	# writer = csv.writer(response)
	# writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
	# writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])
	# writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])
	# writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])
	# writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])
#导出mysql查询出的结果,Django 导出csv文件
	# import csv,codecs
	# sql = "select id,name from operation_student;"
	# info = dao.execSql(sql)
	# response = HttpResponse(content_type='text/csv')
	# response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
	# writer = csv.writer(response)
	# for row in info:
	# 	writer.writerow(row)
	#
	# return response

	# obj = UserGroup.objects.all()
	#增加：
		#1. UserGroup.objects.create(caption="风控组")
	# UserInfo.objects.create(username="xll",password='11111',user_type_id='0',user_group_id=1)#user_group_id外建

	# dict = {
	# 		'ip': '10.1.0.23',
	# 		'hostname': 'gnh-23',
	# 		'product': 'gh',
	# 		'application': 'app'
	# 	}
	# models.Hostlist.objects.create(**dict)


		#2. dic = {"username":"xuliliang","password":"989292","user_type":1}
		#   models.UserInfo.objects.create(**dic)
		#3. obj = models.UserInfo(username="haizeiwang",password='test',user_type='0')
		#  obj.save()

	#删除：
		# models.UserInfo.objects.filter(id=4).delete()
		# models.UserInfo.objects.filter(username='xll').delete()
	#查询：
		# 获取所有数据，QuerySet 类型数据,返回的是列表【obj(id,username,password,),obj,obj】，列表中包含对象
		# result = models.UserInfo.objects.all()
		# for row in result:
		# 	print row.id,row.username,row.password

		# result02 = models.UserInfo.objects.filter(id=5)#相当于where条件
		# result02 = models.UserInfo.objects.values('username','password') #只查询username,password字段

		# result02 = models.UserInfo.objects.filter(id__gt=2)  # 获取id大于2的值
		# result02 = models.UserInfo.objects.filter(id__gte=2)  # 获取id大于等于2的值
		# result02 = models.UserInfo.objects.filter(id__lt=5)		# 获取id小于2的值
		# result02 = models.UserInfo.objects.filter(id__lt=3, id__gt=1)	# 获取id大于1 且 小于10的值
		# result02 = models.UserInfo.objects.filter(id__in=[1, 4, 6])   # 获取id等于1、4、6的数据
		# result02 = models.UserInfo.objects.exclude(id__in=[11, 22, 33])  # not in
		# result02 = models.UserInfo.objects.filter(id__range=[1, 2])   # 范围bettwen and
		# result02 = models.UserInfo.objects.filter(pub_date__isnull=True) # isnull
		# result02 = models.UserInfo.objects.filter(username__contains="test") #
		# result02 = models.UserInfo.objects.filter(username__icontains="test") # icontains大小写不敏感
		# result02 = models.UserInfo.objects.exclude(username__icontains="test") # icontains大小写不敏感
		# result02 = models.UserInfo.objects.order_by('id') #正序
		# result02 = models.UserInfo.objects.filter(username='test').order_by('-id') #倒序


		# result02 = models.UserInfo.objects.filter(id=3)
		# for row in result02:
		# 	print row.id, row.username, row.password,row.user_group_id



	#更新：
		# models.UserInfo.objects.all().update(password='99999')
		# models.UserInfo.objects.filter(id=3).update(password='00000')


from . import models
from permission import  check_permission
# Create your views here.

@check_permission
def students(request):
    students_obj = models.Student.objects.all()
    return render(request, 'students_list.html', locals())



##通过salt获取主机列表

def host_list(request):
	try:
		host_list = HostInfo.objects.all()
	except ValueError:
		pass
	return  render(request,'host_list.html',{'host_list':host_list})

##异步更新host grains信息


def update_host_info(request):
	#判断host主机up状态
	host_list = salt.runner_status('status')['up']
	for host in host_list:
		result = salt.get_minions_grains(host)
		kernel = result['kernel']
		kernel_v = result['kernelrelease']
		kernel = kernel + kernel_v
		num_cpus = result['num_cpus']
		list = result['fqdn_ip4']
		if list :
			ip = result['fqdn_ip4'][0]
		else:
			ip = host
		mem_total = result['mem_total']
		hostname = result['host']
		sn = uuid.uuid1()

		#内存格式化入库
		if mem_total <= 4000:
			mem_total = '4G'
		elif mem_total > 4000 and mem_total <= 8000:
			mem_total = '8G'
		elif mem_total > 8000 and mem_total <= 16000:
			mem_total = '16G'
		info = {
			"ip":ip,
			"kernel":kernel,
			"num_cpus":num_cpus,
			"mem_total":mem_total,
			"hostname":hostname,
			"sn":sn
		}
		print  info
		#判断库中是否有这个ip
		ku_ip = HostInfo.objects.filter(ip=ip)
		if ku_ip:
			print '数据库中已经存在%s的配置信息' % ip
		else:
			HostInfo.objects.create(**info)
	res = 'salt更新成功'
	return  HttpResponse(res)




#远程执行命令
def rem_exec(request):
	res = ''
	host_list = salt.list_all_key()
	host_list = host_list['minions']
	if request.method == 'POST':
		host_ip = request.POST.get('host_ip')
		exec_commond = request.POST.get('exec_commond')
		res = salt.salt_command(host_ip,'cmd.run',exec_commond)
		res = res['return'][0]
		# print type(res)
		# print  res
	else:
		pass
	if request.user.is_authenticated():
		print  'ok'
	else:
		print "^^^^^^^^^^^^^^^^^^^^^"
	return  render(request,'remote_exec_command.html',{'host_list':host_list,'result':res})



#文件下载

#定义从django机器拷贝文件到salt-master机器,需要打通秘要，# 分成put、和get

def remote_scp(remote_path,local_path,tite='get'):
	private_key = paramiko.RSAKey.from_private_key_file('/Users/u51/.ssh/id_rsa')
	t = paramiko.Transport(('10.1.126.23', 22))
	t.connect(username='root', pkey=private_key)
	sftp = paramiko.SFTPClient.from_transport(t)
	if tite == 'get':
		sftp.get(remote_path, local_path)
	elif tite == 'put':
		sftp.put(os.path.abspath(local_path), remote_path)
	t.close()


def file_iterator(file_name, chunk_size=512):
     with open(file_name) as f:
         while True:
             c = f.read(chunk_size)
             if c:
                 yield c
             else:
                 break

def file_down(request):
	file_result = ''
	host_list = salt.list_all_key()
	host_list = host_list['minions']
	if request.method == 'POST':
		ip = request.POST.get('host_ip')
		abs_path= request.POST.get('file_path')
		file_name = abs_path.split('/')[-1] # 等价于os.path.basename(file_path)
		file_path = os.path.dirname(abs_path) + '/'
		file_result = salt.salt_command(ip,'cp.push',file_path+file_name)
		# file_result = salt.look_jid(file_result)
		#拷贝文件到media目录下/var/cache/salt/master/minions/10.1.0.22/files/tmp/22.log
		remote_path = '/var/cache/salt/master/minions/%s/files/%s/%s' % (ip,file_path,file_name)
		local_path  = './media/%s' % (file_name)
		try:
			remote_scp(remote_path,local_path,tite='get')
			response = StreamingHttpResponse(file_iterator(local_path))
			response['Content-Disposition'] = 'attachment;filename="{0}"'.format(file_name)
			response['Content-Type']='application/octet-stream'
			return response
		except:
			ret = u'主机：%s\n结果：远程文件 %s 下载失败，请确认文件是否存在！' % (ip, abs_path)
			return render(request,'salt_file_download.html',{"ret":ret,"host_list":host_list})
	return render(request, 'salt_file_download.html', {"host_list":host_list,"file_result":file_result})

#文件上传



def handle_upload_file(file,filename):
    base_path=settings.UPLOAD_ROOT
    if not os.path.exists(base_path):
		os.makedirs(base_path)
    tmp = random.randint(10000,99999)
    timepath = time.strftime('%Y-%m-%d/',time.localtime(time.time()))
    timestamp = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    new_path = base_path+str(timepath)+str(tmp) + '/'
    # print new_path
    os.makedirs(new_path)
    # print  filename.split('.')[-1] #获取文件后缀
    with open(new_path+filename,'wb+')as destination:
        for chunk in file.chunks():
            destination.write(chunk)
	local_file = new_path+filename
	# print  local_file
	salt_path = '/srv/salt/%s' % (filename)
	# print  salt_path
	remote_scp(salt_path,local_file,tite='put')


def file_upload(request):
	rst = ''
	host_list = []
	if request.method == 'POST':
		myFile = request.FILES.get('myfile',None)  # 获取上传的文件，如果没有文件，则默认为None
		if not myFile:
			# print  "no files for upload!"
			return HttpResponse('no files for upload')
		else:
			handle_upload_file(request.FILES['myfile'], str(request.FILES['myfile']))
			host_ip = request.POST.get('host_ip')
			local_path = 'salt://%s' % (myFile)
			remot_path = '/tmp/%s' % (myFile)
			salt.file_upload(host_ip, 'cp.get_file', local_path, remot_path, 'makedirs=True')
			rst = u'主机：%s\n结果：远程文件 %s 上传成功' % (host_ip, remot_path)
		return render(request, 'salt_file_upload.html', {"rst": rst})
	else:
		# host_list = salt.list_all_key()
		# host_list = host_list['minions']
		# 获取salt fqdn_ip4的ip地址
		host_list = salt.runner_status('status')['up']
		# for host in host_list:
		# 	result = salt.get_minions_grains(host)
		# 	host = result['host']
		# 	list = result['fqdn_ip4']
		# 	host_list.append(list[0])
		return  render(request,'salt_file_upload.html',{"host_list":host_list,"rst":rst})






def vpn_manger(request):
	# 一个页面展示
	PAGE_LIMIT = 10
	pageNo = 0
	all_users = []
	# 参数检查
	if 'pageNo' in request.GET:
		pageNo = request.GET['pageNo']
		# print '===========>' + pageNo
	else:
		pageNo = '0'

	if  isinstance(pageNo,str):
		raise TypeError('pageNo页面传入参数不对')
	else:
		try:
			pageNo = int(pageNo)
			if pageNo < 0:
				pageNo = 0
		except ValueError as ve:
			return HttpResponse('pageNo参数不是int.')

	offset = pageNo * PAGE_LIMIT
	limit =  PAGE_LIMIT

	# if request.method == 'GET':
	#判断是否是搜索，
	search = request.POST.get("get_user", None)
	print '==========>>>>>>>>>>>>>>>' + str(search)
	if search:
		all_users = vpn_mysql.fetch_search(search,offset,limit)
		print  all_users
	else:
		all_users = vpn_mysql.get_all(offset,limit)
		# all_users = {"all_users":all_users,"PAGE_LIMIT":PAGE_LIMIT}

	# print  all_users
	# return HttpResponse('ok')
	content = {"all_users":all_users,"msg":1}
	print all_users[0]['create_time']
	return  render(request,'vpn_manger.html',content)

def vpn_search(request):

	get_user = request.POST.get('get_user')
	# get_user = 'test002'
	print  get_user

	return_json = vpn_mysql.fetch_search(get_user)
	return_json = {'result':return_json}
	print  return_json
	if  return_json:
		return  HttpResponse(json.dumps(return_json),content_type='application/json')

	else:
		return  HttpResponse('查找失败')




def vpn_add(request):
	insert_list = []
	if request.method == 'POST':
		insert_list.append(request.POST.get('user_name'))

		insert_list.append(request.POST.get('user_password'))
		insert_list.append(request.POST.get('name_alias'))
	# insert_list.append(request.POST.get('user_email'))
	# is_active =  request.POST.getlist('is_active')
	# print  insert_list

		row = vpn_mysql.user_insert(insert_list)
		print "==============%s" % (row)
		if  row:
			return_json = {"msg":"用户增加成功"}
			return HttpResponse(json.dumps(return_json),content_type='application/json')
		else:
			return_json = {"msg": "用户名重复"}
			return HttpResponse(json.dumps(return_json), content_type='application/json')
	context = {'currentMenu':'vpn_add'}
	return  render(request,'vpn_add.html',context)

def vpn_update(request,uid):
	if request.method == "GET":
		context = {'currentMenu': 'vpn_update',"uid": uid}
		return render(request, 'passwod_update.html', context)
	elif request.method == 'POST':
		pwd01 = request.POST.get('passwod01')
		pwd02 = request.POST.get('passwod02')
		if pwd01 == pwd02:
			print  '+++++++++%s+++++%s++++%s++' % (uid,pwd01,pwd02)
			res = vpn_mysql.pass_update(pwd01, uid)
			if res:
				return redirect('/op/vpn_manger')
		else:
			return HttpResponse('密码不一致')



def vpn_del(request,aid):
    print  str(aid)
    res = vpn_mysql.vpn_del(aid)
    if res:
		return  redirect('/op/vpn_manger')

    else:
		return  HttpResponse('del fail')



def ajax_add(request):
    a = int(request.GET.get('a'))
    b = int(request.GET.get('b'))
    return_json = {'result':a+b}

    return HttpResponse(json.dumps(return_json), content_type='application/json')


'''文件下载各种方法实例'''
export_file = "./operation/test.csv"
# def file_download(request):
#     # do something...
#     with open(export_file) as f:
#         c = f.read()
#     return HttpResponse(c)


def file_download(request):
	response = StreamingHttpResponse(file_iterator(export_file))
	response['Content-Type'] = 'application/octet-stream'
	response['Content-Disposition'] = 'attachment;filename="{0}"'.format(export_file)
	return response




import redisapi

rsapi = redisapi.RedisApi()

@log_in
def redis_manger(request):
	redis_type = request.POST.get('redis_type')
	redis_key = request.POST.get('redis_key')
	if request.method == "POST" :
		if redis_type == '0':
			print redis_key
			res = rsapi.get_key(redis_key)
			if res:
				return HttpResponse(res)
			else:
				return HttpResponse('空的')
		else:
			rs = rsapi.get_all(redis_key)
			print  rs
			rs = json.dumps(rs)
			return HttpResponse(rs)


	else:
		return  render(request,'redis_manger.html')

	return HttpResponse('okkkk')


def redis_del(request):

	redis_type2 = request.POST.get('redis_type2')
	redis_key2 = request.POST.get('redis_key2')
	if request.method == "POST" :
		if redis_type2 == '0':
			res = rsapi.del_key(redis_key2)
			#if res == 1表示删除成功，0表示失败
			return HttpResponse(json.dumps(res),content_type='application/json')

		else:
			print  'hasget查询'

def redis_set(request):
	return render(request,"redis_set.html")

#获取当前时间
def getNow():
    return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

#获取当前请求url
def _getDetailUrl(request):
    scheme = request.scheme
    host = request.META['HTTP_HOST']
    return "%s://%s/detail/" % (scheme, host)



"""登录认证，包含一个登录失败计数器，5分钟内连续失败5次的账号，会被锁定5分钟"""
from django.contrib.auth.hashers import check_password
login_failure_counter = {} #登录失败锁定计数器，给loginAuthenticate用的
sqlSHA1_cache = {} #存储SQL文本与SHA1值的对应关系，尽量减少与数据库的交互次数,提高效率。格式: {工单ID1:{SQL内容1:sqlSHA1值1, SQL内容2:sqlSHA1值2},}

#ajax接口，登录页面调用，用来验证用户名密码
# @csrf_exempt
def loginAuthenticate(username, password):
    lockCntThreshold = 5
    lockTimeThreshold = 300
    #服务端二次验证参数
    strUsername = username
    strPassword = password
    if strUsername == "" or strPassword == "" or strUsername is None or strPassword is None:
        result = {'status':2, 'msg':'登录用户名或密码为空，请重新输入!', 'data':''}
    elif strUsername in login_failure_counter and login_failure_counter[strUsername]["cnt"] >= lockCntThreshold and (datetime.datetime.now() - login_failure_counter[strUsername]["last_failure_time"]).seconds <= lockTimeThreshold:
        result = {'status':3, 'msg':'登录失败超过5次，该账号已被锁定5分钟!', 'data':''}
    else:
        correct_users = UserInfo.objects.filter(username=strUsername)
        pwd = UserInfo.objects.filter(username=strUsername).values('password')
        print pwd
		# correct_pass = UserInfo.objects.filter(password=strPassword)
        if len(correct_users) == 0:
            result = {'status':4, 'msg':'该用户不存在!', 'data':''}
        elif len(correct_users) == 1  and pwd[0]['password'] == strPassword:
            #调用了django内置函数check_password函数检测输入的密码是否与django默认的PBKDF2算法相匹配
            if strUsername in login_failure_counter:
                #如果登录失败计数器中存在该用户名，则清除之
                login_failure_counter.pop(strUsername)
            result = {'status':0, 'msg':'ok', 'data':''}
        else:
            if strUsername not in login_failure_counter:
                #第一次登录失败，登录失败计数器中不存在该用户，则创建一个该用户的计数器
                login_failure_counter[strUsername] = {"cnt":1, "last_failure_time":datetime.datetime.now()}
            else:
                if (datetime.datetime.now() - login_failure_counter[strUsername]["last_failure_time"]).seconds <= lockTimeThreshold:
                    login_failure_counter[strUsername]["cnt"] += 1
                else:
                    #上一次登录失败时间早于5分钟前，则重新计数。以达到超过5分钟自动解锁的目的。
                    login_failure_counter[strUsername]["cnt"] = 1
                login_failure_counter[strUsername]["last_failure_time"] = datetime.datetime.now()
            result = {'status':1, 'msg':'用户名或密码错误，请重新输入！', 'data':''}
    return result


def authenticateEntry(request):
    """接收http请求，然后把请求中的用户名密码传给loginAuthenticate去验证"""
    if request.is_ajax():
        strUsername = request.POST.get('username')
        strPassword = request.POST.get('password')
    else:
        strUsername = request.POST['username']
        strPassword = request.POST['password']
    result = loginAuthenticate(strUsername, strPassword)
    print '=====================>' + str(result['status'])
    if result['status'] == 0:
        request.session['userid'] = strUsername
        request.session['is_login'] = True
        request.session.set_expiry(7200)
    return HttpResponse(json.dumps(result), content_type='application/json')



##在settings.py中设置operation.views.global_info后就可以使用

leftMenuBtnsCommon = (
                   {'key':'redis_get', 'name':'keys值查询','url':'/op/redis_manger','class':'glyphicon glyphicon-home'},
                   {'key':'redis_set', 'name':'keys值设置','url':'/op/redis_set/','class':'glyphicon glyphicon-asterisk'},
                   {'key':'redis_manager', 'name':'redis监控','url':'/op/redis_monitor/','class':'glyphicon glyphicon-asterisk'},
                   {'key':'charts',     'name':'统计图表展示','url':'/op/charts/','class':'glyphicon glyphicon-file'},
                   {'key':'ftp_upload',     'name':'CDN文件上传','url':'/op/ftp_file_upload/','class':'glyphicon glyphicon-file'},
               )

def global_info(request):
    """存放用户，会话信息等."""
    loginUser = request.session.get('userid', None)
    if loginUser is not None:
		leftMenuBtns = leftMenuBtnsCommon
    else:
    	leftMenuBtns = ()
    return {
        'loginUser':loginUser,
        'leftMenuBtns':leftMenuBtns,
    }


#ftp文件上传,
import commands,shutil,zipfile
import  FtpApi




# @log_in
# def ftp_file_upload(request):
# 	ftpapi = FtpApi.MYFTP()
# 	ftpapi.login()
# 	if request.method == 'GET':
# 		return  render(request,'ftp_upload.html')
# 	else:
# 		myFile = request.FILES.get('fileFolder',None)
# 		mytext = request.POST.get('mytext')
# 		file_name =  myFile.name
# 		local_path = 'media/ftp_upload/'
# 		file_type = os.path.splitext(file_name)[1]
# 		file_qianzhui= os.path.splitext(file_name)[0]
# 		local_file = local_path + file_name
# 		with open(local_path + file_name, 'wb') as f:
# 			for line in myFile.chunks():
# 				f.write(line)
# 				f.close()
#
# 		#保存上传的操作记录
# 		user_name = request.session.get('userid')
# 		url_title = request.path
# 		file_name = file_name
# 		up_path = mytext
# 		dict = {
# 			'user_name':user_name,
# 			'url_title':url_title,
# 			'file_name':file_name,
# 			'up_path':up_path,
# 		}
# 		UserLog.objects.create(**dict)
# 		if file_type == '.zip':
# 			if os.path.exists(local_path + file_qianzhui):
# 				print '解压目录已存在，执行删除操作!!!'
# 				shutil.rmtree(local_path + file_qianzhui + '/')
# 				print "删除目录成功，执行解压文件file.zip  %s" % local_file
# 				(status, output) = commands.getstatusoutput('unzip %s  -d %s ' % (local_file, local_path))
# 			else:
# 				print "开始解压file.zip %s" % local_file
# 				f_zip = zipfile.ZipFile(local_path + file_name, 'r')
# 				f_zip.extractall(local_path)
# 			res = ftpapi.upload_files(local_path + file_qianzhui, mytext)
# 			if res:
# 				print '返回结果%s' % res
# 				print '上传成功后删除目录:%s 和 文件:%s' % (local_path + file_qianzhui, local_path + file_name)
# 				shutil.rmtree(local_path + file_qianzhui + '/')
# 				os.remove(local_path + file_name)
# 				data = 'https://h5.u51.com/99fenqi/' + mytext +''
# 				res_json = json.dumps({'res':res,'msg':'文件上传成功','data':data},ensure_ascii=False)
# 				return HttpResponse(res_json,content_type='application/json')
# 			else:
# 				print '返回结果%s' % res
# 				res_json = json.dumps({'res':res,'msg':'文件上传失败，【请检查】','data':''},ensure_ascii=False)
# 				return HttpResponse(res_json,content_type='application/json')
# 		else:
# 			res = ftpapi.upload_file(local_file, mytext + file_name)
# 			if res==30:
# 				date_str = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
# 				os.rename(local_file,local_file+'_'+date_str)
# 				print '上传成功后备份文件：%s' % local_file+'_'+date_str
# 				# os.remove(local_file)
# 				data = 'https://h5.u51.com/99fenqi/' + mytext + file_name
# 				res_json = json.dumps({'res':res,'msg':'文件上传成功','data':data},ensure_ascii=False)
# 				return HttpResponse(res_json,content_type='application/json')
# 			elif res==20:
# 				os.remove(local_file)
# 				data = 'https://h5.u51.com/99fenqi/' + mytext + file_name
# 				res_json = json.dumps({'res': res, 'msg': '文件相等，跳过不再上传!!!', 'data': data}, ensure_ascii=False)
# 				return HttpResponse(res_json, content_type='application/json')
# 			else:
# 				print '返回结果%s' % res
# 				data = 'https://h5.u51.com/99fenqi/'+mytext+file_name
#
# 				res_json = json.dumps({'res': res, 'msg': '文件上传失败!!!', 'data': ''}, ensure_ascii=False)
#
# 				return HttpResponse(res_json,content_type='application/json')

@log_in
def ftp_file_upload(request):
	if request.method == 'GET':
		return  render(request,'ftp_upload.html')
	else:
		myFile = request.FILES.get('fileFolder',None)
		print  "====33==3=3==>>>>>",myFile
		mytext = request.POST.get('mytext')
		file_name =  myFile.name
		local_path = 'media/ftp_upload/'
		file_type = os.path.splitext(file_name)[1]
		file_qianzhui= os.path.splitext(file_name)[0]
		local_file = local_path + file_name
		with open(local_path + file_name, 'wb') as f:
			for line in myFile.chunks():
				f.write(line)
				f.close()

		#保存上传的操作记录
		user_name = request.session.get('userid')
		url_title = request.path
		file_name = file_name
		up_path = mytext
		dict = {
			'user_name':user_name,
			'url_title':url_title,
			'file_name':file_name,
			'up_path':up_path,
		}
		UserLog.objects.create(**dict)
		if file_type == '.zip':
			if os.path.exists(local_path + file_qianzhui):
				print '解压目录已存在，执行删除操作!!!'
				shutil.rmtree(local_path + file_qianzhui + '/')
				print "删除目录成功，执行解压文件file.zip  %s" % local_file
				(status, output) = commands.getstatusoutput('unzip %s  -d %s ' % (local_file, local_path))
			else:
				print "开始解压file.zip %s" % local_file
				f_zip = zipfile.ZipFile(local_path + file_name, 'r')
				f_zip.extractall(local_path)
			res = FtpApi.upload_files_to(local_path + file_qianzhui, mytext)
			if res:
				print '返回结果%s' % res
				print '上传成功后删除目录:%s 和 文件:%s' % (local_path + file_qianzhui, local_path + file_name)
				shutil.rmtree(local_path + file_qianzhui + '/')
				os.remove(local_path + file_name)
				data = 'https://h5.u51.com/99fenqi/' + mytext +''
				res_json = json.dumps({'res':res,'msg':'文件上传成功','data':data},ensure_ascii=False)
				return HttpResponse(res_json,content_type='application/json')
			else:
				print '返回结果%s' % res
				res_json = json.dumps({'res':res,'msg':'文件上传失败，【请检查】','data':''},ensure_ascii=False)
				return HttpResponse(res_json,content_type='application/json')
		else:
			res = FtpApi.upload_file_to(local_file, mytext + file_name)
			if res==True:
				date_str = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
				os.rename(local_file,local_file+'_'+date_str)
				print '上传成功后备份文件：%s' % local_file+'_'+date_str
				# os.remove(local_file)
				data = 'https://h5.u51.com/99fenqi/' + mytext + file_name
				res_json = json.dumps({'res':res,'msg':'文件上传成功','data':data},ensure_ascii=False)
				return HttpResponse(res_json,content_type='application/json')
			else:
				print '返回结果%s' % res
				data = 'https://h5.u51.com/99fenqi/'+mytext+file_name

				res_json = json.dumps({'res': res, 'msg': '文件上传失败!!!', 'data': ''}, ensure_ascii=False)

				return HttpResponse(res_json,content_type='application/json')



def ftp_upload(request):
	if request.method == 'GET':
		return  render(request,'ftp_upload.html')
	else:
		myFile = request.FILES.get('file',None)
		mytext = request.POST.get('checkText')
		file_name =  myFile.name
		local_path = 'media/ftp_upload/'
		file_type = os.path.splitext(file_name)[1]
		file_qianzhui= os.path.splitext(file_name)[0]

		local_file = local_path + file_name
		with open(local_path + file_name, 'wb') as f:
			for line in myFile.chunks():
				f.write(line)
				f.close()

		# 保存上传的操作记录
		user_name = request.session.get('userid')
		url_title = request.path
		file_name = file_name
		up_path = mytext
		dict = {
			'user_name': user_name,
			'url_title': url_title,
			'file_name': file_name,
			'up_path': up_path,
		}
		# UserLog.objects.create(**dict)
		if file_type == '.zip':
			if os.path.exists(local_path + file_qianzhui):
				print '解压目录已存在，执行删除操作!!!'
				shutil.rmtree(local_path + file_qianzhui + '/')
				print "删除目录成功，执行解压文件file.zip  %s" % local_file
				(status, output) = commands.getstatusoutput('unzip %s  -d %s ' % (local_file, local_path))
			else:
				print "开始解压file.zip %s" % local_file
				f_zip = zipfile.ZipFile(local_path + file_name, 'r')
				f_zip.extractall(local_path)
			res = FtpApi.upload_files_to(local_path + file_qianzhui, mytext)
			if res:
				print '返回结果%s' % res
				print '上传成功后删除目录:%s 和 文件:%s' % (local_path + file_qianzhui, local_path + file_name)
				shutil.rmtree(local_path + file_qianzhui + '/')
				os.remove(local_path + file_name)
				data = 'https://h5.u51.com/99fenqi/' + mytext + ''
				res_json = json.dumps({'res': res, 'msg': '文件上传成功', 'data': data}, ensure_ascii=False)
				return HttpResponse(res_json, content_type='application/json')
			else:
				print '返回结果%s' % res
				res_json = json.dumps({'res': res, 'msg': '文件上传失败，【请检查】', 'data': ''}, ensure_ascii=False)
				return HttpResponse(res_json, content_type='application/json')
		else:
			res = FtpApi.upload_file_to(local_file, mytext + file_name)
			if res == True:
				date_str = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
				os.rename(local_file, local_file + '_' + date_str)
				print '上传成功后备份文件：%s' % local_file + '_' + date_str
				# os.remove(local_file)
				data = 'https://h5.u51.com/99fenqi/' + mytext + file_name
				res_json = json.dumps({'res': res, 'msg': '文件上传成功', 'data': data}, ensure_ascii=False)
				return HttpResponse(res_json, content_type='application/json')
			else:
				print '返回结果%s' % res
				data = 'https://h5.u51.com/99fenqi/' + mytext + file_name
				res_json = json.dumps({'res': res, 'msg': '文件上传失败!!!', 'data': ''}, ensure_ascii=False)
				return HttpResponse(res_json, content_type='application/json')


#审计操作记录
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

def userlog(request):
	contacts=UserLog.objects.all().order_by('-create_time')
	paginator = Paginator(contacts,10)
	count = paginator.count
	page_range = paginator.page_range
	num_pages = paginator.num_pages
	page = request.GET.get('page',default=1)
	page = int(page)
	try:
		contacts = paginator.page(page)
	except PageNotAnInteger:
		contacts = paginator.page(1)
	except EmptyPage:
		contacts = paginator.page(paginator.num_pages)
	if num_pages > 11:
		if page - 5 < 1:
			page_range = range(1, 11)
		elif page + 5 > paginator.num_pages:
			page_range = range(page - 5, page + 1)
		else:
			page_range = range(page - 5, page + 6)
	else:
		page_range = page_range
	print  num_pages
	print page_range
	return  render(request,'user_log.html',{'contacts':contacts,'page_range':page_range,'num_pages':num_pages,'count':count})



#图形charts展示
def charts(request):
	context = {'currentMenu': 'charts'}
	return render(request, 'charts.html', context)
# 获取图表数据
from  .dao import Dao
dao = Dao()
def getMonthCharts(request):
	result = dao.getWorkChartsByMonth()
	print  result

	return HttpResponse(json.dumps(result), content_type='application/json')

def getPersonCharts(request):
	result = dao.getWorkChartsByPerson()
	return HttpResponse(json.dumps(result), content_type='application/json')

#web terminal

def webssh(request):
	if request.method=='GET':
		return  render(request,'webssh.html')




def connecthost(request):
	host_sn = request.POST.get('host_id')
	obj = HostInfo.objects.get(sn=host_sn)
	obj_ip = obj.ip
	obj_host_user = obj.host_user
	obj_pass = obj.host_passwd
	obj_prot = obj.host_remove_port
	print obj_ip

	return HttpResponse(host_sn)


# import argparse
#	argparse模块使编写用户友好的命令行界面变得容易。程序定义了它需要的参数，argparse将找出如何从sys.argv中解析这些参数。argparse模块还自动生成帮助和用法消息，并在用户向程序提供无效参数时发出错误。
# 	parser = argparse.ArgumentParser(description='Process some integers.')
# 	parser.add_argument('integers', metavar='N', type=int, nargs='+',
# 						help='an integer for the accumulator')
# 	parser.add_argument('--sum', dest='accumulate', action='store_const',
# 						const=sum, default=max,
# 						help='sum the integers (default: find the max)')
#
# 	args = parser.parse_args()
# 	print(args.accumulate(args.integers))


#导航菜单
# def nav(request):
#
# 	return  render(request,'nav.html')

from django.forms  import forms
from  DjangoUeditor.forms import UEditorField



class TestUEditorForm(forms.Form):
    content = UEditorField('内容', width=600, height=300, toolbars="full", imagePath="images/", filePath="files/",
                           upload_settings={"imageMaxSize": 1204000},
                           settings={})


def ud2(request):
	form = TestUEditorForm()
	return render(request, 'ueditor.html', {'form': form})






###########################
#定义rest接口
###########################

from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from .serializers import UserSerializer, GroupSerializer,ProductSerializer,SnippetSerializer





class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer



class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer

class ProductViewSet(viewsets.ModelViewSet):
	queryset = Product.objects.all()
	serializer_class = ProductSerializer




from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view(['GET', 'POST'])
def nav(request):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        snippets = User.objects.all().order_by('-date_joined')
        serializer = SnippetSerializer(snippets, many=True)
        return Response(snippets)

    elif request.method == 'POST':
        serializer = SnippetSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


def FileUploads(request):
    file = request.FILES.get('file')  # 获取文件对象，包括文件名文件大小和文件内容
    curttime = time.strftime("%Y%m%d")
    #规定上传目录
    upload_url = os.path.join(settings.MEDIA_ROOT,'attachment',curttime)
    #判断文件夹是否存在
    folder = os.path.exists(upload_url)
    if not folder:
        os.makedirs(upload_url)
        print("创建文件夹")
    if file:
        file_name = file.name
        #判断文件是是否重名，懒得写随机函数，重名了，文件名加时间
        if os.path.exists(os.path.join(upload_url,file_name)):
            name, etx = os.path.splitext(file_name)
            addtime = time.strftime("%Y%m%d%H%M%S")
            finally_name = name + "_" + addtime + etx
            #print(name, etx, finally_name)
        else:
            finally_name = file.name
 		#文件分块上传
        upload_file_to = open(os.path.join(upload_url, finally_name), 'wb+')
        for chunk in file.chunks():
            upload_file_to.write(chunk)
        upload_file_to.close()
		#返回文件的URl
        file_upload_url = settings.MEDIA_URL + 'attachment/' + curttime + '/' +finally_name
        #构建返回值
        response_data = {}
        response_data['FileName'] = file_name
        response_data['FileUrl'] = file_upload_url
        response_json_data = json.dumps(response_data)#转化为Json格式
        return HttpResponse(response_json_data)
